package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Question;
import cn.wolfcode.luowowo.article.domain.QuestionTag;
import cn.wolfcode.luowowo.article.mapper.QuestionMapper;
import cn.wolfcode.luowowo.article.mapper.QuestionTagMapper;
import cn.wolfcode.luowowo.article.service.IQuestionService;
import cn.wolfcode.luowowo.common.query.QuestionQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionTagMapper tagMapper;

    public PageInfo query(QuestionQueryObject qo) {
        return null;
    }


    public AjaxResult saveOrUpdate(Question content, UserInfo user) {
        AjaxResult result = new AjaxResult();
        //设置作者
        content.setAuthor(user);
        if (content.getId() == null) {

            content.setQuestionTime(new Date());
            questionMapper.insert(content);
        } else {
            //更新问答表
            questionMapper.updateByPrimaryKey(content);
        }

        List<QuestionTag> tags = content.getTags();
        //设置标签
        if (tags != null && tags.size() > 0) {
            for (QuestionTag tag : tags) {
                //判断是否存在
                QuestionTag questionTag = tagMapper.selectByName(tag.getName());
                //不存在才保存
                if (questionTag == null) {
                    tagMapper.insert(tag);
                }
                //维护关系
                tagMapper.insertRelation(tag.getId(), content.getId());
            }
        }

        return result.addData(content.getId());
    }


    public List<Question> queryAll() {
        return questionMapper.selectAll();
    }


    public Question queryById(Long id) {
        Question question = questionMapper.selectByPrimaryKey(id);

        return question;
    }

    @Override
    public void incrAnswernum(Long id) {
        int answerNum = questionMapper.getAnswerNum(id);
        questionMapper.incrAnswernum(answerNum + 1, id);
    }

    @Override
    public void updateStatus(Long id, int status) {
        questionMapper.updateStatus(id,status);
    }
}
